import {useContext, useState} from 'react';
import { places } from './data.js';
import './index.scss'
import {ImageSizeContext} from './Context'
import classNames from "classnames";

export default function ContextTest() {
  const [isLarge, setIsLarge] = useState(false);
  const imageSize = isLarge ? 150 : 100;
  return (
    <>
      <label>
        <input
          type="checkbox"
          checked={isLarge}
          onChange={e => {
            setIsLarge(e.target.checked);
          }}
        />
        Use large images
      </label>
      <hr />
      <ImageSizeContext.Provider value={imageSize}>
        <List/>
      </ImageSizeContext.Provider>
    </>
  )
}

function List() {
  const [activeIndex, setActiveIndex] = useState(-1)
  const listItems = places.map((place, index) =>
    <li
      key={place.id}
      onClick={() => setActiveIndex(index)}
      className={classNames({'active': activeIndex === index})}
    >
      <Place
        place={place}
      />
    </li>
  );
  return <ul>{listItems}</ul>;
}

function Place({ place }) {
  return (
    <>
      <PlaceImage
        place={place}
      />
      <p>
        <b>{place.name}</b>
        {': ' + place.description}
      </p>
    </>
  );
}

function PlaceImage({ place }) {
  const imageSize = useContext(ImageSizeContext)
  return (
    <img
      src='https://ts1.cn.mm.bing.net/th/id/R-C.8d52fd88fbacb0bc34afa0d3e3d3fbf0?rik=YLBGQ2YxYJczDg&riu=http%3a%2f%2fwww.08lr.cn%2fuploads%2fallimg%2f220330%2f1-2300134436.jpg&ehk=h6QkPS87X6L6Vb7h5F10YmPZlLWLGKOMcKNcY9zMLRA%3d&risl=&pid=ImgRaw&r=0'
      alt={place.name}
      width={imageSize}
      height={imageSize}
    />
  );
}
